package com.yanqu.road.dao.impl.union;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.union.UserUnionWarMark;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserUnionWarMarkImpl extends TempDataObjectDao<UserUnionWarMark> {

	public UserUnionWarMark getUserUnionWarMark(long userId) {
		ResultSet rs = null;
		CallableStatement call = null;
		String sql = "select * from t_u_union_war_mark where userId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareCall(sql);
			call.setLong(1, userId);
			rs = call.executeQuery();
			while (rs.next()) {
				UserUnionWarMark data = parse(rs);
				return data;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return null;
	}

	@Override
	protected boolean addData(UserUnionWarMark data) {
		PreparedStatement call = null;
		String sql = "INSERT INTO t_u_union_war_mark(userId,rankRewardMark,unionRewardMark,watchBattleMark) VALUES(?,?,?,?)";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setLong(i++, data.getUserId());
			call.setInt(i++, data.getRankRewardMark());
			call.setInt(i++, data.getUnionRewardMark());
			call.setInt(i++, data.getWatchBattleMark());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected boolean updateData(UserUnionWarMark data) {
		PreparedStatement call = null;
		String sql = "UPDATE t_u_union_war_mark SET rankRewardMark=?,unionRewardMark=?,watchBattleMark=? WHERE userId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setInt(i++, data.getRankRewardMark());
			call.setInt(i++, data.getUnionRewardMark());
			call.setInt(i++, data.getWatchBattleMark());
			call.setLong(i++, data.getUserId());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected UserUnionWarMark parseData(ResultSet rs) throws SQLException {
		UserUnionWarMark data = new UserUnionWarMark();
		data.setUserId(rs.getLong("userId"));
		data.setRankRewardMark(rs.getInt("rankRewardMark"));
		data.setUnionRewardMark(rs.getInt("unionRewardMark"));
		data.setWatchBattleMark(rs.getInt("watchBattleMark"));
		return data;
	}
}
